<?php

namespace App\Service\VendorClient\Shophltmsp;

use App\Service\Code\Normal;
use App\Service\BaseService;
use App\Model\PssModel\ServiceConfig;
use Service\AppService\IdService;
use App\Service\TaskServer\TaskWorker;

/**
 * 海旅会员购上游对接(一般贸易)SDK
 * @author hj
 */
class ShophltmspApiClient extends BaseService {
    //供应商编号
    const SUPPLIER_CODE = 'shophltmsp';

    //配置文件
    private $config = [];

    public function __construct($apiBody = []) {
        $this->config = $apiBody;
    }

    /**
     * 创建订单
     * @param array $params
     * @return array
     */
    public function createOrder($param = []) {
        if (empty($param['supplierOrder']) || empty($param['orderGoods']) || empty($param['order']) || empty($param['binfo'])) {
            return Normal::returnCode(Normal::FAIL, "except param supplierOrder or orderGoods or order or binfo");
        }
        $orderInfo = $param['supplierOrder'];
        $goodsList = $param['orderGoods'];
        $order     = $param['order'];
        $binfo     = $param['binfo'];
        $order_sn  = $orderInfo['supplier_dsn'];
        //订单时间
        $order_time = $orderInfo['cd'] ? date('Y-m-d H:i:s', $orderInfo['cd']) : date('Y-m-d H:i:s', time());
        //支付时间
        $pay_time = isset($order['payTime']) && !empty($order['payTime']) ? date('Y-m-d H:i:s', $order['payTime']) : date('Y-m-d H:i:s', time());
        //运费分摊
        $deliver_money = $orderInfo['deliver_money'];
        //下单支付的时候支付信息
        $apply_extends = @json_decode($orderInfo['apply_extends'], true);
        //获取下单商品信息
        $palceOrderGoods = [];
        $goodsTotalMoney = '0.00';
        foreach ($goodsList as $key => $item) {
            $tax_rate         = bcadd('1', (string)$item['tax_rate'], 4);
            $price            = $item['price'];
            $spec_num         = $item['spec_num'];
            $quantity         = $item['quantity'];
            $supplier_skucode = $item['supplier_skucode'];
            $goods_type       = $item['goods_type'];
            //实际购买数量(下单数量 X 起售数量)
            $buyAcount        = $spec_num * $quantity;
            $realGoodsProce   = bcdiv((string)$price, (string)$spec_num, 3);
            $realGoodsProce   = ceil((float)$realGoodsProce * 100) / 100;
            $singleGoodsMoney = bcmul($realGoodsProce, (string)$buyAcount, 2);
            $goodsTotalMoney  = bcadd((string)$goodsTotalMoney, $singleGoodsMoney, 2);
            //下单商品组
            $goodsInfo         = [
                'active_cut' => $realGoodsProce,//活动价(单位:元)
                'barcode'    => trim($item['supplier_skucode']),//编码
                'cit_cnname' => $item['goods_name'],//名称
                'cit_code'   => trim($item['supplier_commodity_key']),//条码
                'count'      => $buyAcount,//数量
                'price'      => $realGoodsProce,//价格(单位:元)
            ];
            $palceOrderGoods[] = $goodsInfo;
        }
        //订单金额
        $totalMoney = bcadd((string)$goodsTotalMoney, (string)$deliver_money, 2);
        //用户实际支付金额
        $real_total_money = $orderInfo['real_total_money'];
        //订单优惠金额
        $discount_money = bcsub((string)$totalMoney, (string)$real_total_money, 2);
        $requestParam   = [
            'bonus_money'             => 0,//红包金额
            'coupon_code'             => '',//用户优惠券券码
            'coupon_money'            => 0,//优惠券优惠额度,(单位:元)
            'create_time'             => strtotime($order_time),//创建时间
            'is_pre_sale'             => 0,//是否预售单[0-否,1-是],默认0
            'discount_money'          => 0,//折扣金额(单位:元
            'express_money'           => 0,//运费,默认0
            'mer_order_sn'            => $order_sn,//订单号
            'pay_time'                => strtotime($pay_time),//支付时间
            //订单级别:
            // real_pay_money和price一样就好，就是商品单价乘以数量
            // express_money和discount_money都固定为0
            // 订单商品级别
            // active_cut和price都传一样的，就是商品单价
            'price'                   => $real_total_money,//订单金额(单位:元)
            'real_pay_money'          => $real_total_money,//实际支付金额(单位:元)
            'receiver_address_detail' => $orderInfo['receive_address'],//详细地址
            'receiver_city_name'      => $orderInfo['city'],//市
            'user_id'                 => 0,//海旅用户id,默认0。(使用优惠券务必传user_id)
            'receiver_district_name'  => $orderInfo['district'],//县/区
            'receiver_mobile'         => $orderInfo['recveive_phone'],//接收人手机号
            'receiver_name'           => $orderInfo['receive_name'],//姓名
            'receiver_province_name'  => $orderInfo['province'],//收件人省
            'receiver_street_name'    => $orderInfo['district'],//街道
            'trade_number'            => $order['paySerial'] ?? $apply_extends['paySerial'],//第三方支付单号
            'goods'                   => $palceOrderGoods,//下单商品列表
        ];
        $data           = [
            'method' => 'createOrder',
            'data'   => $requestParam,
        ];
        return $this->execute($data);
    }

    /**
     * 商品列表查询
     * @param $data
     * @return array
     */
    public function queryGoodsList($param = []) {
        $page  = $param['page'] ?? 1;
        $limit = $param['limit'] ?? 50;
        $data  = [
            'method' => 'goodsList',
            'data'   => [
                'page'      => $page,//页数
                'page_size' => $limit,//每页条数
            ],
        ];
        $res1  = $this->execute($data);
        if ($res1['code'] != Normal::SUC) {
            return Normal::returnCode(Normal::FAIL, "当前商品列表数据获取异常");
        }
        if (!isset($res1['data']['data']['list']) || empty($res1['data']['data']['list'])) {
            return Normal::returnCode(Normal::SUC, '获取完成', ['total' => 0, 'data' => []]);
        }
        $data = $res1['data']['data']['list'];
        return Normal::returnCode(Normal::SUC, '获取成功', ['total' => count($data), 'data' => $data]);
    }

    /**
     * 商品详情查询
     * @param $data
     * @return array
     */
    public function queryGoodsDetail($params = []) {
        $data = [
            'method' => 'goodsDetailBatch',
            'data'   => [
                'barcode'   => $params['supplierSkuCode'],//商品编码 数组
                'page_size' => count($params['supplierSkuCode']),
                'page'      => 1
            ],
        ];
        return $this->execute($data);
    }

    /**
     * 订单详情查询
     * @param $data
     * @return array
     */
    public function queryOrderDetail($params = []) {
        $data = [
            'method' => 'orderDetail',
            'data'   => [
                'mer_order_sn' => [$params['orderSn']],//订单号
            ],
        ];
        return $this->execute($data);
    }

    /**
     * 物流轨迹查询
     * @param $data
     * @return array
     */
    public function queryExpressLogistics($params = []) {
        $data = [
            'method' => 'expressLogistics',
            'data'   => [
                'express_no' => $params['expressNo'],//物流单号
            ],
        ];
        return $this->execute($data);
    }

    /**
     * 申请退款接口
     * @param $data
     * @return array
     */
    public function orderAfterSale($params = []) {
        $data = [
            'method' => 'orderAfterSale',
            'data'   => [
                'order_sn'      => $params['supplierOrder']['thirdpart_order_sn'],//订单号
                'mer_orderid'   => $params['supplierOrder']['supplier_dsn'],//商户订单号
                'user_mobile'   => $params['supplierOrder']['buyer_phone'],//用户手机号
                'user_name'     => $params['supplierOrder']['buyer_realname'],//用户名称
                'refund_money'  => $params['supplierOrder']['real_total_money'],//退款金额
                'refund_reason' => $params['order']['exceptReason'] ?? '人工运营处理售后退款',//原因
                'refund_desc'   => $params['order']['exceptReason'] ?? '人工运营处理售后退款',//描述
            ],
        ];
        return $this->execute($data);
    }

    /**
     * 签名
     * @param $tsp
     * @return string
     */
    public function sign($tsp) {
        $data = [
            'mer_code'  => $this->config['appId'],
            'timestamp' => $tsp,
        ];
        $strA = '';
        foreach ($data as $k => $v) {
            $strA .= "{$k}={$v}&";
        }
        $strB = $strA . $this->config['appSecret'];
        return strtoupper(md5($strB));
    }

    /**
     * CURL请求
     * @param $params
     * @return array
     */
    public function execute($param = []) {
        $method = $param['method'];
        $data   = $param['data'];
        if (!isset($this->config[$method])) {
            return Normal::returnCode(Normal::FAIL, "请求方法名称未设置");
        }
        if (empty($param['data'])) {
            return Normal::returnCode(Normal::FAIL, "接口请求数据不能为空");
        }
        $baseUrl = $this->config['baseUrl'] ?? '';
        if (empty($baseUrl)) {
            return Normal::returnCode(Normal::FAIL, "接口请求地址不能为空");
        }
        $url       = $this->config['baseUrl'] . $this->config[$method];
        $tsp       = time();
        $pushData  = [
            'mer_code'  => $this->config['appId'],
            'timestamp' => $tsp,
            'sign'      => $this->sign($tsp),
            'data'      => $param['data'],
        ];
        $parameter = [
            [
                'tag'    => self::SUPPLIER_CODE . '_' . $param['method'],
                'uid'    => IdService::instance()->getOtherID(),
                'url'    => $url,
                'data'   => $pushData,
                'method' => 'post',
                'format' => 'json',
                'header' => [
                    "Content-Type: application/json"
                ],
            ],
        ];
        // $resTask   = TaskWorker::instance()->addTask($parameter);
        if( in_array($param['method'],['goodsList']) ) {
            $resTask = TaskWorker::instance()->addTask($parameter,'handleDiableTask');
        } else {
            $resTask = TaskWorker::instance()->addTask($parameter);
        }
        $resTask   = current($resTask);
        $result    = @json_decode($resTask['response']['result'], true);
        if (isset($result['code']) && $result['code'] == 200) {
            return Normal::returnCode(Normal::SUC, "操作成功", $result);
        }
        $msg = $result['message'] ?? '请求失败';
        return Normal::returnCode(Normal::FAIL, $msg, $result);
    }
}